package com.atguigu.service;

import com.atguigu.exception.CustomException;
import com.atguigu.mapper.AdminMapper;
import com.atguigu.pojo.Account;
import com.atguigu.pojo.Admin;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import jakarta.annotation.Resource;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class AdminService {

    @Resource
    private AdminMapper adminMapper;


    public void add(Admin admin) {
        String username = admin.getUsername();
        Admin dbAdmin= adminMapper.selectByUsername(username);
        if (dbAdmin!= null) {

            throw new CustomException("500", "账号已存在，请更换账号");
        }
        admin.setRole("ADM");
        adminMapper.add(admin);
    }

    public void deleteById(Integer id) {
        adminMapper.deleteById(id);
    }

    public void update(Admin admin) {
        adminMapper.update(admin);
    }

    public List<Admin> selectAll(Admin admin) {
        return adminMapper.selectAll(admin);
    }

    public Admin selectById(Integer id) {
        return adminMapper.selectById(id);
    }

    public PageInfo<Admin> selectPage(Admin admin, Integer pageNum, Integer pageSize) {
        PageHelper.startPage(pageNum, pageSize);
        List<Admin> list = adminMapper.selectAll(admin);
        return PageInfo.of(list);
    }


    public void deleteBatch(List<Integer> ids) {
        for(Integer id : ids) {
            adminMapper.deleteById(id);
        }
    }

    public Admin login(Account account) {
        String username = account.getUsername();
        Admin dbAdmin= adminMapper.selectByUsername(username);
        if(dbAdmin== null) {//查不到
            throw new CustomException("500", "账号不存在！");
        }

        String password = account.getPassword();
        if(!dbAdmin.getPassword().equals(password)) {
            throw new CustomException("500", "账号或者密码错误！");
        }
        return dbAdmin;
    }

    public void updatePassword(Account account) {
        Integer id = account.getId();
        Admin dbAdmin = adminMapper.selectById(id);
        if(!dbAdmin.getPassword().equals(account.getPassword())) {
            throw new CustomException("500", "原密码错误！");
        }
        dbAdmin.setPassword(account.getPassword());
        this.update(dbAdmin);
    }
}
